import { reqgetcate, reqgetgoods } from "../../http/api"

// state 
const initState = {
    cate: [],
    goods: [],
}

// action type
const TYPES = {
    CATE_CATE: "CATE_CATE",
    CATE_GOODS: "CATE_GOODS"
}

// reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.CATE_CATE:
            return {
                ...state,
                cate: action.cate
            }
        case TYPES.CATE_GOODS:
            return {
                ...state,
                goods: action.goods
            }
        default:
            return state
    }
}

// action creator
export const actions = {
    changeCate: cate => ({ type: TYPES.CATE_CATE, cate }),
    reqCate: () => (dispatch, getState) => {
        let cate = getCate(getState())
        if (cate.length > 0) {
            return
        }
        reqgetcate().then(res => {
            if (res.data.code === 200) {
                dispatch(actions.changeCate(res.data.list))
            }
        })
    },
    changeGoods: goods => ({ type: TYPES.CATE_GOODS, goods }),
    reqGoods: (fid = 1) => (dispatch, getState) => {
        reqgetgoods({ fid }).then(res => {
            if (res.data.code === 200) {
                dispatch(actions.changeGoods(res.data.list))
            }
        })
    },
}

// selector导出数据给组件
export const getCate = state => state.cate.cate
export const getGoods = state => state.cate.goods

// 导出reducer
export default reducer